﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;

namespace Robert.TwitBy.Converters
{
    class RemainingCharsConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var s = value as string;
            int remainingChars;

            if (!s.StartsWith("d "))
                remainingChars = 140 - s.Length;
            else
            {
                string user;
                if (s.Length >= 4)
                    user = new Func<string, string>(p =>
                        {
                            int i = 2;
                            string final = null;
                            while ((char.IsLetterOrDigit(p[i]) || p[i] == '_') && i + 1 < p.Length)
                            {
                                final += p[i];
                                i++;
                            }
                            return final;
                        }).Invoke(s);
                else
                    return 140 - s.Length;

                remainingChars = (140 + user.Length + 3) - s.Length;
            }

            return remainingChars;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
